from optparse import OptionParser
import re, os
from util import run_command

class Ocr(object):
	
	def __init__(self, tesseract_path, ghostscript_path, lang):
		self.__tesseract_path = tesseract_path
		self.__ghostscript_path = ghostscript_path
		self.__lang = lang
	
	def analyze(self, pdf_file):
		tif_file = pdf_file + '.tif'
		txt_file = tif_file + '.txt'
		
		if self.__convert_to_tif(pdf_file, tif_file) != 0:
			raise Exception('Error converting PDF to TIF')
		
		if self.__run_ocr(tif_file) != 0:
			raise Exception('Error during tesseract OCR call')
		
		all_words = self.__get_words_from_file(txt_file)
		all_words = filter(lambda x: len(x) > 3, all_words)
		
		os.remove(tif_file)
		os.remove(txt_file)
		
		return all_words

	def __convert_to_tif(self, pdffile, tiffile):
		return run_command(self.__ghostscript_path, [ "-q", "-dNOPAUSE", "-dBATCH", "-dSAFER", "-r300x300", "-sDEVICE=tiffg3", "\"-sOutputFile="+tiffile+"\"", "-c", "save", "pop", "-f\""+pdffile +"\""])

	def __run_ocr(self, tiffile):
		return run_command(self.__tesseract_path, [ '"'+tiffile+'"', '"'+tiffile+'"', "-l", self.__lang ])

	def __get_words_from_string(self, s):
		return set(re.findall(re.compile('\w+'), s.lower()))

	def __get_words_from_file(self, fname):
		with open(fname, 'rb') as inf:
			return self.__get_words_from_string(inf.read())


if __name__ == "__main__":
	ocr = Ocr('/usr/local/bin/tesseract', '/opt/local/bin/gs', 'fra')
	print ocr.analyze('test.pdf')
